import router from '../index'
import { Notification } from 'element-ui'
import { getAuthMenuList } from '@/apiList/loginAuth'
import { session } from '@/utils/jcore/storage'
import { notFoundRouter } from './staticRouter'
import { LOGIN_URL } from '@/config/config'
import { getShowMenuList } from '../routerUtils'
import blank from '@/views/common/blank.vue'
import store from '@/store'

/**引入 views/pages 文件夹下所有 vue 文件 */
const modules = import.meta.glob('@/views/pages/**/*.vue')

/**根据菜单添加动态路由 */
function addDynamicRoute(menuList) {
  for (let item of menuList) {
    const comp = item.component
    if (comp && typeof comp === 'string') {
      const loadPath = `/src/views/pages${comp}.vue`
      const component = modules[loadPath]
      if (!component) {
        console.warn(`未找到 [${loadPath}] 页面，请检查路由配置`)
        console.log(item)
      }
      const r = {
        ...item,
        component: component || blank // 未找到页面添加空白页面补位
      }
      if (item.meta.isFull) {
        // 如果是全屏页面
        router.addRoute(r)
      } else {
        // 非全屏页面添加侧边布局
        router.addRoute('layout', r)
      }
    }
    if (Array.isArray(item.children)) {
      addDynamicRoute(item.children)
    }
  }
}

/**
 * 初始化动态路由
 */
export async function initDynamicRouter() {
  try {
    // 1.获取菜单列表
    const authMenuListGet = await getAuthMenuList()

    // 1.1 根据菜单同步侧边栏数据
    store.dispatch('app/setMenuList', getShowMenuList(authMenuListGet))

    // 2.判断当前用户有没有菜单权限
    if (!authMenuListGet.length) {
      Notification({
        title: '无权限访问',
        message: '当前账号无任何菜单权限，请联系系统管理员！',
        type: 'warning',
        duration: 3000
      })
      session.clear()
      router.replace(LOGIN_URL)
      return Promise.reject('没有权限')
    }

    // 3.添加动态路由
    addDynamicRoute(authMenuListGet)

    // 4.最后添加 notFoundRouter
    router.addRoute(notFoundRouter)
  } catch (error) {
    // 💢 当菜单请求出错时，重定向到登陆页
    session.clear()
    router.replace(LOGIN_URL)
    return Promise.reject(error)
  }
}
